<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '500px',
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      },
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = () => {
      if (this.chart) {
        this.chart.resize()
      }
    }
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)

      const nodes = this.chart._chartsViews[0]._data._graphicEls
      let allNode = 0
      for (let index = 0; index < nodes.length; index++) {
        const node = nodes[index]
        if (node === undefined) {
          continue
        }
        allNode++
      }

      const height = window.innerHeight
      const width = window.innerWidth - 1000
      const currentHeight = 85 * allNode
      const currentWidth = 155 * allNode
      const newHeight = Math.max(currentHeight, height)
      const newWidth = Math.max(currentWidth, width)
      const tree_ele = this.$el
      // tree_ele.style.height = newHeight + 'px'; //设置高度自适应
      tree_ele.style.width = newWidth + 'px' //设置宽度自适应
      this.chart.resize()

      // this.chart.on('click', this.chartData.clickCallback) //节点点击事件
      this.$emit('getMychart', this.chart)
    },
    setOptions(data) {
      this.chart.setOption({
        series: [
          {
            type: 'tree',
            orient: 'TB', //竖向或水平  TB代表竖向 LR代表水平
            top: '5%',
            left:'5%',
            initialTreeDepth: 4, //树图初始展开的层级（深度）
            expandAndCollapse: false, //点击节点时不收起子节点，default: true
            // symbolSize: [135, 65],
            itemStyle: {
              color: 'transparent',
              borderWidth: 0,
            },
            edgeShape: 'polyline', // 连线直角
            // roam: true, // 平移缩放
            lineStyle: {
              color: '#D5D5D5',
              width: 1,
              curveness: 1,
            },
            select:{
              itemStyle:{
                color:"red"
              }
            },
            data: [data],
          },
        ],
      })
    },
    sidebarResizeHandler(e) {
      if (e.propertyName === 'width') {
        this.__resizeHandler()
      }
    },
  },
}
</script>